package com.example.lab05.repository.Impl;


import com.example.lab05.entity.Member;
import com.example.lab05.repository.GenericRepository;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.thymeleaf.util.StringUtils;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

public class GenericRepositoryImpl<T extends Serializable,ID extends Number> implements GenericRepository<T,ID> {

    @Autowired
    private SqlSession sqlSession;


    private String namespace;

    @SuppressWarnings("unchecked")
    public GenericRepositoryImpl() {
        ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
        Class<T> clazz = (Class<T>) parameterizedType.getActualTypeArguments()[0];
        namespace = StringUtils.unCapitalize(clazz.getSimpleName());
    }
    private String getStatement(String Sql){
        return namespace.concat(".").concat(Sql);
    }
    @Override
    public List<T> queryAll() {
        return sqlSession.selectList(getStatement("queryAll"));
    }

    @Override
    public void create(T t) {
         sqlSession.insert(getStatement("create"),t);
    }

    @Override
    public void removeById(ID id) {
        sqlSession.delete(getStatement("remove"),id);
    }

    @Override
    public void modify(T t) {
        sqlSession.update(getStatement("modify"),t);
    }

    @Override
    public T queryById(ID id) {
        return sqlSession.selectOne(getStatement("queryById"),id);
    }

    @Override
    public T query(String sqlId, Object parameter) {
        return sqlSession.selectOne(getStatement(sqlId),parameter);
    }

    @Override
    public List<T> queryList(String sqlId, Object parameter) {
        return sqlSession.selectList(getStatement(sqlId),parameter);
    }
}
